package cn.huobi.system.service.impl;

import cn.huobi.system.domain.Menu;
import cn.huobi.system.mapper.MenuMapper;
import cn.huobi.system.service.IMenuService;
import cn.huobi.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huobi
 * @since 2022-10-24
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 一级菜单查询
     * @return
     */
    @Override
    public List<Menu> first() {
        List<Menu> menus = menuMapper.findAll();
        List<Menu> list = menus.stream().filter(menu -> menu.getParentId() == null).collect(Collectors.toList());

//        List<Menu> list = new ArrayList<>();
//        for (Menu menu : menus) {
//            if (menu.getParentId() == null){
//                list.add(menu);
//            }
//        }
        return list;
    }

    /**
     * 菜单联级 无极限树
     * @return
     */
    @Override
    public List<Menu> tree() {
        // 查询全部菜单
        List<Menu> menus = menuMapper.findAll();

        List<Menu> result = new ArrayList<>();
        Map<Long, Menu> menuMap = menus.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        menus.forEach(menu -> {
            if (menu.getParentId() == null){
                result.add(menu);
            }else {
                Menu parent = menuMap.get(menu.getParentId());
                if (parent == null){
                    return;
                }
                parent.getChildren().add(menu);
            }
        });
        return result;
    }
}
